package com.sqeakecleanblog.mediaplayer.view
{
	import com.sqeakecleanblog.mediaplayer.ApplicationFacade;
	import com.sqeakecleanblog.mediaplayer.components.FullScreenControlPanel;
	import com.sqeakecleanblog.mediaplayer.components.MediaControls;
	import com.sqeakecleanblog.mediaplayer.components.TVScreen;
	
	import flash.display.*;
	import flash.events.FullScreenEvent;
	
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class StageMediator extends Mediator
	{
		public static const NAME:String = "StageMediator";
		
		private var _screen:TVScreen;
		private var _panel:MediaControls;
		private var _fullScreenCntrl:FullScreenControlPanel;
		
		public function get stage():Stage
		{
			return viewComponent as Stage;
		}
		
		public function StageMediator(viewComponent:Stage)
		{
			super(NAME, viewComponent);
		}
		
		override public function onRegister():void
		{
			_screen = facade.retrieveMediator(MediaPlayerMediator.NAME).getViewComponent() as TVScreen;
			_panel = facade.retrieveMediator(MediaControlsMediator.NAME).getViewComponent() as MediaControls;
			_fullScreenCntrl = new FullScreenControlPanel(_panel.getControls());
			
			positionAssets();
			
			stage.addChild(_screen);
			stage.addChild(_panel);
			
			stage.addEventListener(FullScreenEvent.FULL_SCREEN, onFullScreen);
			
			sendNotification(ApplicationFacade.APP_INIT, stage);
		}
		
		override public function listNotificationInterests():Array
		{
			return [
					ApplicationFacade.FULL_SCREEN
					];
		}
		
		override public function handleNotification(notification:INotification):void
		{
			switch(notification.getName())
			{
				case ApplicationFacade.FULL_SCREEN:
					fullScreenEvent();
					break;
			}
		}
		
		private function positionAssets():void
		{
			_screen.x = (stage.stageWidth - _screen.width)/2;
			_screen.y = (stage.stageHeight - (_screen.height + _panel.height))/2;
			
			_panel.x = (stage.stageWidth - _panel.width)/2;
			_panel.y = _screen.y + _screen.height;
		}
		
		private function onFullScreen(e:FullScreenEvent):void
		{
			e.fullScreen ? setFullScreen() : setNormalScreen();
		}
		
		private function fullScreenEvent():void
		{
			stage.displayState = stage.displayState == StageDisplayState.NORMAL ? StageDisplayState.FULL_SCREEN : StageDisplayState.NORMAL;
		}
		
		private function setFullScreen():void
		{
			_panel.visible = false;
			
			_fullScreenCntrl.x = (stage.stageWidth - _fullScreenCntrl.width)/2;
			_fullScreenCntrl.y = stage.stageHeight - _fullScreenCntrl.height;
			stage.addChild(_fullScreenCntrl);
			_fullScreenCntrl.setFullScreen();
			_screen.fullScreen();
		}
		
		private function setNormalScreen():void
		{
			_fullScreenCntrl.setNormalScreen();
			_panel.visible = true;
			_panel.reset();
			_screen.normalScreen();
		}
		
	}
}